/**
 * 
 */
package org.jlambda.util;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;

public class ByteBufferToReadableByteChannel implements ReadableByteChannel {

	private ByteBuffer buffer = null;
	boolean closed = false;
	
	public ByteBufferToReadableByteChannel(ByteBuffer buffer){
		this.buffer  = buffer;
	}
	
	public int read(ByteBuffer dst) throws IOException {
		int rem = buffer.remaining();
		if (rem == 0) return -1; // finished the stream
		int copy = (dst.limit() < rem) ? dst.limit() : rem;
		byte[] bytes = new byte[copy];
		buffer.get(bytes);
		dst.put(bytes);
		return copy;
	}

	public boolean isOpen() {
		return (closed || buffer.hasRemaining());
	}

	public void close() throws IOException {
		// noop.
		closed = true;
	}
	
}